﻿#include "UDPListener.h"
#include <QDateTime>
#include <QDebug>
UDPListener::UDPListener(QObject *parent) : QObject(parent)
{
    socket = new QUdpSocket(this);
    qDebug() << "socket->bind = " << socket->bind(QHostAddress::AnyIPv4, 8888);
    // 使用 bind 函数监听
    // 一个 QUdpSocket 只能监听一个端口
    connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
}

void UDPListener::onReadyRead()
{
    qDebug() << "onReadyRead()";
    QHostAddress addr;
    quint16 port;
    int size;
    while((size = socket->pendingDatagramSize()) > 0)
    {
        QByteArray data;
        data.resize(size);
        socket->readDatagram(data.data(), data.size(), &addr, &port);
        QDateTime dt = QDateTime::currentDateTime();
        QString timestr = dt.toString("yyyyMMddhhmmss");
        qDebug() << data;
        QString str = data;

        if(str.contains("eDEVICE_L_RearRobotInterruptUpZ"))
        {
            qDebug() << "robotLoading(LEFT_ROBOT)";
            emit robotLoading(LEFT_ROBOT);
            return;
        }
        if(str.contains("eDEVICE_R_RearRobotInterruptUpZ"))
        {
            qDebug() << "robotLoading(RIGHT_ROBOT)";
            emit robotLoading(RIGHT_ROBOT);
            return;
        }
        QStringList list = str.split(",");
        if(list.size() == 4)
        {
            //qDebug() <<"error:" << list;
            QString cmd = list.at(0).trimmed();
            QString recipe = list.at(1).trimmed();
            QString left_id = list.at(2).trimmed();
            QString right_id = list.at(3).trimmed();
            if(cmd == "eDEVICE_L")
            {
                //emit trigger(LEFT_ROBOT, recipe, left_id, right_id);
                emit trigger(LEFT_ROBOT, recipe, right_id, left_id);
            }
            else
            {
                //emit trigger(RIGHT_ROBOT, recipe, left_id, right_id);
                emit trigger(RIGHT_ROBOT, recipe, right_id, left_id);
            }
        }
    }
}
